package wili.json;

import wili.c.Ca;
import wili.c.Str9a;

/**
 * 串|字面值; 串值可被解析成其它表达式或值。
 */
public class JsonLeaf extends JsonNode {
	public Object value;

	public String toString() {
		return "i" + this.id + "," + this.attName + ": " + this.stringValue + ", NL" + this.lineNo;
		//return "leaf: " + stringValue + ", NL" + this.lineNo;
	}

	public JsonLeaf(JsonFile0 file, int start, JsonNode dad) {
		// attName 随后在JsonObj 中生成
		super(file, start, dad);
		if (this.stringValue.equals("true")) {
			this.value = true;
		} else if (this.stringValue.equals("false")) {
			this.value = false;
		} else {
			this.value = Str9a.simpleValueOfStr(this.stringValue, null);
		}
		if (id == 165)
			Ca.pause();
		String st = this.getString(false);
		if (st.startsWith("="))
			Ca.pause();
	}

	public JsonLeaf(String attName, Object value) {
		super(attName);
		this.stringValue = value.toString();
		this.value = value;
	}

	public boolean matchValue(Object obj) {
		if (obj == null || "null".equals(obj))
			return this.stringValue.equals("null");
		if (this.value != null && this.value.equals(obj) || this.stringValue.equals(obj))
			return true;
		if (obj instanceof String) {
			String st = (String) obj;
			return st.equals(this.stringValue);
		} else if (obj instanceof Integer) {
			try {
				Integer ret = Integer.parseInt(this.stringValue);
				return ret.equals(obj);
			} catch (Exception e) {
				return false;
			}
		} else if (obj instanceof Boolean) {
			if (this.stringValue.matches("true|false") || this.value instanceof Boolean) {
				return obj.equals(this.stringValue) || obj.equals(this.value);
			}
		} else {
			Ca.asert(false, "NOT_SUPPORT_TYPE: " + obj.getClass().getName());
		}
		return false;
	}

	@Override
	void saveToBuffer(String dent, StringBuilder buf) {
		//buf.append("i" + id + ":");
		if (id == 21531)
			Ca.pause();
		if (this.value == null || this.value instanceof String) {
			String st = quote2(this.stringValue);
			if (st.contains("null"))
				Ca.pause();
			buf.append(st);
		} else {
			buf.append(value);
		}
	}
}
